package helper

import (
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/test/gtest"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/sony/sonyflake"
	"strconv"
	"time"
)

var Helper = helper{}

type helper struct {
	environment string
}

// development 本地开发环境
// testing 测试环境
// production 生产环境

func (r helper) SetEnvironment(environment string) helper {
	r.environment = environment

	return r
}
func (r helper) GetEnvironment() string {
	if r.environment == "" {
		val, err := g.Config().Get(gctx.New(), "testing.env")
		if err != nil {
			panic(err)
		}

		r.environment = val.String()
	}

	return r.environment
}

func (r helper) GetUrl(path string) string {
	val, err := g.Config().Get(gctx.New(), fmt.Sprintf("testing.%s.endpoint", r.GetEnvironment()))
	if err != nil {
		panic(err)
	}

	return val.String() + path
}
func (r helper) GetToken() string {
	val, err := g.Config().Get(gctx.New(), fmt.Sprintf("testing.%s.token", r.GetEnvironment()))
	if err != nil {
		panic(err)
	}

	return "Bearer " + val.String()
}

func (r helper) AssertCode(t *gtest.T, code string) {
	t.Assert(len(code), 23)

	codes := gstr.Explode("-", code)
	t.Assert(len(codes), 4)
	for _, code := range codes {
		t.Assert(len(code), 5)
		fmt.Println(code)
	}
}

func GetTransactionId() string {
	s := time.Date(2009, 5, 1, 0, 0, 0, 0, time.UTC)
	r := sonyflake.NewSonyflake(sonyflake.Settings{
		StartTime: s,
	})

	for {
		id, err := r.NextID()
		if err == nil {
			return strconv.FormatUint(id, 10)
		}
	}
}
